package work.chenbo.springboot.security.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import work.chenbo.springboot.security.config.properties.SecurityProperties;
import work.chenbo.starter.common.util.ImageCodeUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ChenBo
 * @className LoginController
 * @date 2020/11/5
 */
@Controller
@RequiredArgsConstructor
@Slf4j
public class LoginController {


    private final SecurityProperties securityProperties;

    @GetMapping("/login")
    public String Login(){
        return "login";
    }


    @GetMapping("/code/image")
    public void getImageCode(HttpServletRequest request, HttpServletResponse response){

        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            SecurityProperties.ImageCode imageCode = securityProperties.getImageCode();
            int width = ServletRequestUtils.getIntParameter(request, "width", imageCode.getWidth());
            int height = ServletRequestUtils.getIntParameter(request, "height", imageCode.getHeight());
            ImageCodeUtils.ImageCode img = ImageCodeUtils.getImageCode(width, height, imageCode.getLength(), imageCode.getTimeout());
            HttpSession session = request.getSession();
            session.setAttribute("SESSION_KEY_IMAGE_CODE",img);
            ImageIO.write(img.getImage(),"PNG",outputStream);
        } catch (IOException e) {
            log.error("获取图像验证码异常",e);
        }

    }
}
